import { App, Directive } from 'vue'

const debounce = (fn: Function, delay: number) => {
  let timer: NodeJS.Timeout
  return (...args: any[]) => {
    clearTimeout(timer)
    timer = setTimeout(() => {
      fn(...args)
    }, delay)
  }
}

export const vDebounce: Directive = {
  mounted(el, binding) {
    const { value, arg = 300 } = binding
    console.error(binding)
    if (typeof value !== 'function') {
      throw new Error(
        'v-debounce must receive a function as value,eg: v-debounce="()=>{}"'
      )
    }
    el.addEventListener('click', debounce(value, Number(arg)))
  },
}

const install = (app: App) => {
  app.directive('debounce', vDebounce)
}

export default install
